package com.zpark.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * TODO
 *
 * @Description 自定义局部过滤器
 * @Author zhangbing
 * @Date 2024/4/23 9:04
 **/
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {

    static final String PARAM_NAME="param";
    public MyParamGatewayFilterFactory() {

        super(MyParamGatewayFilterFactory.Config.class);
    }


    //按照顺序进行赋值到Config对象中
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }

    //方法 apply 应用
    // Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
    @Override
    public GatewayFilter apply(Config config) {
        //服务交换器 过滤器链
        return (exchange,chain)->{
            //获取请求参数的param对应的参数名的参数值
            ServerHttpRequest request = exchange.getRequest();
            if(request.getQueryParams().containsKey(config.param)){
                request.getQueryParams().get(config.param).forEach(value-> System.out.printf("----局部过滤---%s = %s---",config.param,value));
            }
            return chain.filter(exchange);
        };
    }


    public static class Config{
       private String param;  //配置文件中的name

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
